package com.bsj.travel.mqtt.cluster;

import com.bsj.travel.mqtt.enums.RedisKeys;
import lombok.RequiredArgsConstructor;
import net.dreamlu.iot.mqtt.core.server.model.Message;
import net.dreamlu.iot.mqtt.core.server.serializer.IMessageSerializer;
import net.dreamlu.iot.mqtt.core.server.store.IMqttMessageStore;
import net.dreamlu.mica.core.utils.CharPool;
import net.dreamlu.mica.redis.cache.MicaRedisCache;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yinhao
 * @version 1.0
 * @description mqtt遗嘱信息存储redis
 * @date 2023/11/9
 */
@RequiredArgsConstructor
public class MessageStoreRedis implements IMqttMessageStore {
    private final MicaRedisCache redisCache;
    private final IMessageSerializer messageSerializer;

    /**
     * 添加遗嘱信息
     * @param clientId
     * @param message
     * @return
     */
    @Override
    public boolean addWillMessage(String clientId, Message message) {
        redisCache.set(RedisKeys.MESSAGE_STORE_WILL.getKey(clientId), message, messageSerializer::serialize);
        return true;
    }

    /**
     * 清楚遗嘱信息
     * @param clientId
     * @return
     */
    @Override
    public boolean clearWillMessage(String clientId) {
        redisCache.del(RedisKeys.MESSAGE_STORE_WILL.getKey(clientId));
        return true;
    }

    /**
     * 获取遗嘱信息
     * @param clientId
     * @return
     */
    @Override
    public Message getWillMessage(String clientId) {
        return redisCache.get(RedisKeys.MESSAGE_STORE_WILL.getKey(clientId), messageSerializer::deserialize);
    }

    @Override
    public boolean addRetainMessage(String topic, Message message) {
        redisCache.hSet(RedisKeys.MESSAGE_STORE_RETAIN.getKey(), topic, messageSerializer.serialize(message));
        return true;
    }

    @Override
    public boolean clearRetainMessage(String topic) {
        redisCache.hDel(RedisKeys.MESSAGE_STORE_RETAIN.getKey(), topic);
        return true;
    }

    @Override
    public List<Message> getRetainMessage(String topicFilter) {
        List<Message> retainMessageList = new ArrayList<>();
        RedisKeys redisKeys = RedisKeys.MESSAGE_STORE_RETAIN;
        String redisKeyPrefix = redisKeys.getKey();
        Message message = messageSerializer.deserialize(redisCache.hGet(redisKeyPrefix, topicFilter));
        retainMessageList.add(message);
        return retainMessageList;
    }

    /**
     * 转换成redis的pattern规则
     * @param topicFilter
     * @return
     */
    private static String getTopicPattern(String topicFilter) {
        //mqtt 分享主题 $share/{shareName}/{filter}
        return topicFilter.replace(CharPool.PLUS, CharPool.STAR)
                .replace(CharPool.HASH, CharPool.STAR);
    }
}
